// pages/poster/poster.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    petInfo: {},
    canvasToTempFilePath: '',
    imgWidth: 0,
    imgheight: 0,
    petImage: '',
    openStatus: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.petId = options.petId;
    that.detailPet();
  },
  detailPet: function(){
    wx.showLoading();
    let that = this;
    let fn = res => {
      if(res.data.code == 200){
        let _petInfo = res.data.data;
        that.setData({
          petInfo: _petInfo
        })
        wx.getImageInfo({ 
          src: _petInfo.petImgs[0].url, 
          success: function (res) { 
            that.setData({
              imgWidth: res.width*3,
              imgheight: res.height*3,
              petImage: res.path
            });
            that.createPoster();
          } 
        }) 
      }
    }
    app.ajax('/petAdopt/list/detail?id=' + that.petId, 'get', '', fn)
  },
  createPoster: function (){
    wx.getSystemInfo({
      success: (result) => {
        console.info('screenHeight'+result.screenHeight);
        console.info('screenWidth'+result.screenWidth);
      },
    })
    let that = this;
    const ctx = wx.createCanvasContext('poster-canvas');
    
    //绘制背景
    ctx.drawImage('/image/pet/background.jpg', 0, 0, 690, 1085);
    //绘制小程序吗
    ctx.drawImage('/image/xch_code.jpg', 440, 865, 200, 200);
    //平台介绍
    ctx.setFillStyle('#740af8'); // 文字颜色
    ctx.setFontSize(42); // 文字字号
    ctx.setShadow(2, 2, 2, '#dbdbdb');
    ctx.fillText('爱物回家平台', 50, 920); // 绘制文字
    ctx.setFontSize(36); // 文字字号
    ctx.fillText('流浪动物领养平台', 50, 990); // 绘制文字
    ctx.setFontSize(32); // 文字字号
    ctx.fillText('领养/寻宠/寻主/动物收容', 50, 1050); // 绘制文字
    //绘制海报框
    ctx.fillStyle = '#fff';//填充白色
    ctx.beginPath();
    ctx.rect(50, 50, 590, 800);
    ctx.fill();
    ctx.clip();
 
    //绘制宠物图片
    let width = that.data.imgWidth, height = that.data.imgheight;
    if (width > 0 && height > 0){
      let left = 0, top = 0, drawWidth = 0, drawHeight = 0;
      if(width > height){ //宽图
        drawWidth = width > 590 ? 590 : width;
        drawHeight = width > 590 ? (590*height)/width : height;
      }else{ //长图
        drawHeight = height > 800 ? 800 : height;
        drawWidth = height > 800 ?  (800*width)/height : width;
      }
      top = (800 -drawHeight)/2;
      left = ((590-drawWidth)/2) + 50;    
      console.info("drawImage param left top drawWidth drawHeight->"+left+' '+top+' '+drawWidth+' '+drawHeight); 
      ctx.drawImage(that.data.petImage, left, top, drawWidth, drawHeight);
    }
    //绘制文字
    ctx.restore();
    ctx.setFillStyle('#565656'); // 文字颜色
    ctx.setFontSize(27); // 文字字号
    let petText = '我叫'+ that.data.petInfo.nickName +',是个'+ (that.data.petInfo.sex==1?'男孩':'女孩')+',我在合肥市你在哪里';
    ctx.fillText(petText, 80, 700); // 绘制文字
    ctx.setFillStyle('#eb6b24'); // 文字颜色
    ctx.setFontSize(38); // 文字字号
    ctx.fillText('——带 我 回 家 好 不 好——', 100, 800); // 绘制文字


    ctx.draw(false, function () {
      // canvas画布转成图片并返回图片地址
      wx.canvasToTempFilePath({
        canvasId: 'poster-canvas',
        success: function (res) {
          let canvasToTempFilePath = res.tempFilePath
          that.setData({
            canvasToTempFilePath: canvasToTempFilePath
          })
        },
        fail: function () {
          wx.showToast({
            title: '绘制失败',
          })
        },
        complete: function () {
          wx.hideLoading()
        }
      })
    })
  },
  savePoster: function(){
    let that = this;
    let openStatus = that.data.openStatus;
    // 获取用户是否开启用户授权相册
    if (!openStatus) {
      wx.openSetting({
        success: (result) => {
          if (result) {
            if (result.authSetting["scope.writePhotosAlbum"] === true) {
              openStatus = true;
              wx.saveImageToPhotosAlbum({
                filePath: that.data.canvasToTempFilePath,
                success() {
                  that.setData({
                    showShareImg: false
                  })
                  wx.showToast({
                    title: '图片保存成功，快去分享到朋友圈吧~',
                    icon: 'none',
                    duration: 2000
                  })
                },
                fail() {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          }
        },
        fail: () => { },
        complete: () => { }
      });
    } else {
      wx.getSetting({
        success(res) {
          // 如果没有则获取授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                openStatus = true
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    that.setData({
                      showShareImg: false
                    })
                    wx.showToast({
                      title: '图片保存成功，快去分享到朋友圈吧~',
                      icon: 'none',
                      duration: 2000
                    })
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail() {
                // 如果用户拒绝过或没有授权，则再次打开授权窗口
                openStatus = false
                console.log('请设置允许访问相册')
                wx.showToast({
                  title: '请设置允许访问相册',
                  icon: 'none'
                })
              }
            })
          } else {
            // 有则直接保存
            openStatus = true
            wx.saveImageToPhotosAlbum({
              filePath: that.data.canvasToTempFilePath,
              success() {
                that.setData({
                  showShareImg: false
                })
                wx.showToast({
                  title: '图片保存成功，快去分享到朋友圈吧~',
                  icon: 'none',
                  duration: 2000
                })
              },
              fail() {
                wx.showToast({
                  title: '保存失败',
                  icon: 'none'
                })
              }
            })
          }
        },
        fail(err) {
          console.log(err)
        }
      })
    }
  }
})